<template>
  <div class="main">
    <!--    {{ imageList }}-->
<!--    {{ testdata }}-->
<!--    {{ videoList }}-->
<!--    {{ imageList }}-->
    <div class="nav">
      <img :src="back" alt="" @click="handleBack" class="back"/>
      <span>发布{{ publishTitle }}</span>
    </div>
    <div class="content" v-loading="loading">
      <el-input
          placeholder="写一个标题更有可能被推荐~(选填)"
          maxlength="20"
          show-word-limit
          v-model="title"
      ></el-input>
      <el-input
          placeholder="即时分享内容"
          maxlength="500"
          show-word-limit
          type="textarea"
          v-model="content"
          rows="5"
          resize="none"
      ></el-input>
      <div class="detail-content">
        <div class="category" v-if="topicList.length > 0">选择话题类别{{ typeLength }}/4</div>
        <div class="topic-list" v-if="topicList.length > 0">
          <div
              class="topic-item"
              v-for="(item, index) in topicList"
              :key="index"
              :class="{ selected: isSelected(index) }"
              @click="toggleSelection(index)"
          >
            #{{ item.name }}
          </div>
        </div>
        <div class="img-list">
          <!-- v-if="imageList.length > 0" -->
          <!-- 图片 -->
          <div
              class="img-item-detail"
              v-if="imageList.length > 0"
              v-for="(item, index) in imageList"
              :key="index">
            <div style="position:relative">
              <img :src="store.state.imgUrl+item" alt="" width="110" height="110">
              <!-- <img :src="item" width="122" height="122"/> -->
              <i class="el-icon-remove"
                 style="color:#f29600;margin-left:2px;font-size:17px;position:absolute;top:-10px;right:2px"
                 @click="handleDel(index)"></i>
            </div>
          </div>
          <!-- 添加图片 -->
          <div class="img-item" v-if="imageList.length < 9 && publishTitle =='动态'" @click="handleOpen">
            <img :src="addImage" class="bigImg"/>
            <div>{{ imageList.length }}/9</div>
          </div>
          <!--          添加视频-->
          <div class="img-item" v-if=" videoList.length == 0&&publishTitle=='视频' " @click="handleOpenVideo">
            <img :src="addImage" class="bigImg"/>
            <!-- <img :src="testImg" alt="" class="img"> -->
            <!--            <div>{{ // imageList.length }}/9</div>-->
          </div>
        </div>
        <!-- 视频占位区 -->
        <div style="margin:10px 0">
          <video
              v-if="videoList.length > 0"
              id="myVideo"
              alt="my video"
              controls
              crossorigin="anonymous"
              width="50%">
            <source :src="store.state.imgUrl+videoList[0]" type="video/mp4"/>
            Your browser does not support the video tag.
          </video>
          <img
              v-if="coverImage"
              :src="coverImage"
              alt="video cover image"
              width="30%"
          />
        </div>
      </div>
      <div class="is_lock">
        <!-- <span>观看权限</span> -->
        <van-cell center :title="isOneself ? '公开可见' : '仅自己可见'">
          <template #right-icon>
            <van-switch v-model="isOneself" size="24" active-color="#f29600"/>
          </template>
        </van-cell>
        <!-- <div v-if="isOneself" @click="gotoIsOpen">
          <img src="@/assets/Lock_Open.png" />
          <div>公开可见</div>
        </div>
        <div v-if="!isOneself" @click="gotoIsOpen">
          <img src="@/assets/Lock.png" />
          <div>仅自己可见</div>
        </div> -->
      </div>
    </div>
    <div class="footer">
      <div class="btn" @click="publish">发布</div>
    </div>

  </div>
</template>

<script>
import {Toast} from "vant";
import {publishChoose, publish} from "../../../api/share";
import FileUpload from "../components/file-upload";
import Axios from "@/utils/request";
import store from '@/store'
import {antiShake} from '@/utils/antie.js'//防抖函数

export default {
  components: {
    FileUpload,
  },
  name: "sy",
  data() {
    return {
      store: store,
      loading: false,
      coverImage: null,
      addImage: require("@/assets/addImage.png"),
      back: require("@/assets/search/back.png"),
      title: "",
      content: "",
      topicList: [],
      imageList: [], //上传的图片集合
      videoList: [], //上传的视频集合
      show: false,
      imgSrc: "",
      selectedTopics: [],
      types: [],
      commentType: 0, //0文章1动态2视频
      publishTitle: "文章",
      isOneself: true, //仅自己可见 0:是1：否
      token: "",
      type: "",
      typeLength: 0,
      testVedio: 'https://debug.yasee.com.cn/admin/sys-file/yaseeoss/c710fc39e6364e2d9b8f6a63447f8df9.mp4',
      // testVedio:'./test.mp4',
      showLock: false,
      actions: [{name: '公开可见'}, {name: '仅自己可见'}],
      titleLock: '公开可见'
    };
  },
  computed: {
    imageAction() {
      return `${this.$store.state.baseUrlSecond}/image/upload`;
    },
  },
  mounted() {
    // this.handleFirstImg(); // 处理视频的第一帧作为封面
    window["getInfoFromFlutter"] = (info) => {
      if (JSON.parse(info).action === 'upload') {
        this.getInfoFromFlutter(info);
      }
    };

    this.commentType = this.getParam("commentType")
        ? this.getParam("commentType")
        : "";
    this.token = this.getParam("token")
        ? decodeURI(this.getParam("token"))
        : "";
    switch (this.commentType) {
      case "0":
        this.publishTitle = "文章";
        break;
      case "1":
        this.publishTitle = "动态";
        break;
      case "2":
        this.publishTitle = "视频";
        break;
    }
    this.getContent();

  },
  methods: {
    onRead(files) {
      this.files = files;
    },
    handleFirstImg() {
      const video = document.getElementById("myVideo");
      console.log(video)
      video.addEventListener(
          "loadedmetadata",
          () => {
            // 设置视频的暂停位置为0.01秒，以获取第一帧画面
            video.currentTime = 0.01;
          },
          false
      );
      video.addEventListener("seeked", () => {
        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");

        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;

        // 将视频的第一帧绘制到canvas上
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        // 将canvas上的图片转换为base64格式的数据

        this.coverImage = canvas.toDataURL();

      })
    },
    // 获取参数
    getParam(name) {
      if (window.location.hash.indexOf("?") != -1) {
        const query = window.location.hash.split("?")[1];
        const vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
          var pair = vars[i].split("=");
          if (pair[0] == name) {
            return pair[1];
          }
        }
      } else {
        return "";
      }
    },
    getInfoFromFlutter(info) {
      let data = JSON.parse(info);
      // this.testdata = data
      if (data.param.type == "image") {
        // if (data.param.images && data.param.images.length > 0) {
          this.imageList.push(data.param.urls[0]);
        // }
      } else if (data.param.type == 'video') {
        // if (data.param.videos && data.param.videos.length > 0) {
          this.videoList = data.param.urls;
          this.handleFirstImg()//获取视频的第一帧
        // }
      }
    },
    gotoIsOpen() {
      this.isOneself = !this.isOneself;
    },
    isSelected(index) {
      return this.selectedTopics.includes(index);
    },
    toggleSelection(index) {
      if (this.isSelected(index)) {
        // 如果已选中，则取消选中
        const selectedIndex = this.selectedTopics.indexOf(index);
        this.selectedTopics.splice(selectedIndex, 1);
        this.types.splice(this.topicList[index], 1); //删除选中的标签
      } else {
        if (this.typeLength === 4) {
          this.$toast("话题类别数量超出限制");
        } else {
          // 如果未选中，则添加到已选中列表
          this.types.push(this.topicList[index].id);
          this.selectedTopics.push(index);
          // console.log('selected', this.types)
        }
      }
      this.typeLength = this.types.length;
      // console.log(this.types)
    },
    getContent() {
      let data = {
        token: this.token,
      };
      publishChoose(data).then((res) => {
        this.topicList = res.data;
      });
    },
    publish: antiShake(function () {
      this.loading = true
      let data = {
        commentType: this.videoList.length > 0 ? 2 : this.commentType,
        isOneself: this.isOneself == false ? 0 : 1,
        title: this.title,
        description: this.content,
        types: this.types.length > 0 ? this.types.join(",") : "",
        mediaContent: this.videoList[0], // 1动态(视频链接)2视频(视频链接)
        textContent: this.commentType == 0 ? "" : this.imageList.join(","), //0文章(文本内容)1动态(图片链接)
        token: this.token,
        thumbnail: this.coverImage ? this.coverImage : undefined
      };
      console.log("publish-data", data);
      if (this.content && this.types.length > 0) {
        publish(data)
            .then((res) => {
              if (res.code == 0) {
                this.$toast.success("发布成功，待审核");
                this.loading = false
                this.$router.go(-1);
              }
            })
            .catch((err) => {
              this.$toast.fail("发布失败");
              this.loading = false
            });
      } else {
        if (!this.content) {
          this.$toast("发布内容不能为空");
          this.loading = false
        } else if (this.types.length == 0) {
          this.$toast("话题类别不能为空");
          this.loading = false
        }
      }
    }),
    handleBack() {
      //返回
      let message = {//返回时发送事件传递空数组清空上次选中图片状态
        action: "update",
        param: {
          type: "image", //必填
          images: [],
        },
      };
      getInfoFromVue.postMessage(JSON.stringify(message));
      this.$router.go(-1);
      if (this.publishTitle == '动态') {
        let message1 = {
          action: 'showBottom',
          param: {}
        }
        getInfoFromVue.postMessage(JSON.stringify(message1))
      }
    },
    handleFileUpload(e) {
      let file = e.target.files[0].name;
      // 执行你的文件处理逻辑，例如上传到服务器或展示预览图等
      console.log(file);
      this.$toast.success(file);
      // 清除已选择的文件
      // event.target.value = '';
    },

    clickFile() {
      this.$refs.leftFile.click();
    },
    handleOpen() {
      // this.show = true
      // let data = {
      //   type: "image",  //必填
      //   callback: 1  //必填
      // }
      let message = {
        action: "upload",
        param: {
          type: "image", //必填
        },
      };
      getInfoFromVue.postMessage(JSON.stringify(message));
      // this.videoList.push(this.testVedio)
    },
    handleOpenVideo() {
      let message = {
        action: "upload",
        param: {
          type: "video", //必填
        },
      };
      getInfoFromVue.postMessage(JSON.stringify(message));
    },
    handleDel(index) {
      //删除图片
      this.imageList.splice(index, 1)
      //删除图片时传递图片数组清空已删除图片的选中状态
      let message = {
        action: "update",
        param: {
          type: "image", //必填
          images: this.imageList,
        },
      };
      getInfoFromVue.postMessage(JSON.stringify(message));
    }

  },
};
</script>

<style scoped lang="less">
.main {
  height: 100vh;

  .nav {
    display: flex;
    height: 33px;
    background: #f29600;
    justify-content: flex-start;
    align-items: center;
    flex-direction: row;
    padding: 4px 16px 7px 16px;

    > span {
      font-size: 20px;
      font-weight: 500;
      color: rgba(255, 255, 255, 1);
      text-align: center;
      padding-left: 129px;
    }
  }

  .content {

    /deep/ .el-input--small .el-input__inner {
      height: 60px;
      line-height: 60px;
    }

    /deep/ .el-input .el-input__count {
      font-size: 17px;
    }

    /deep/ input::placeholder {
      //color: rgb(25, 24, 24);
      font-size: 17px;
    }

    /deep/ .el-input--small {
      font-size: 17px;
    }

    /deep/ .el-textarea .el-input__count {
      font-size: 17px;
    }


    /deep/ .el-input__inner {
      border: none;
      border-bottom: 0.45px solid rgba(229, 229, 229, 1);
    }

    /deep/ .el-textarea__inner {
      border: none;
    }

    /deep/ .el-textarea__inner {
      font-size: 15px;
    }

    .detail-content {
      padding: 0 10px;

      .category {
        font-size: 17px;
        font-weight: 400;
        color: rgba(166, 166, 166, 1);
        text-align: left;
      }

      ::-webkit-scrollbar {
        display: none;
      }

      .topic-list {
        padding-top: 12px;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        overflow-x: scroll;

        .selected {
          background-color: rgba(242, 150, 0, 1);
          border-color: rgba(242, 150, 0, 1) !important;
          color: #ffffff !important;
        }

        .topic-item {
          flex-shrink: 0;
          width: calc((100% - 18px) / 4);
          height: 27px;
          margin-right: 6px;
          line-height: 27px;
          text-align: center;
          opacity: 1;
          border-radius: 13.5px;
          border: 1px solid rgba(166, 166, 166, 1);
          font-size: 17px;
          font-weight: 400;
          color: rgba(56, 56, 56, 1);
        }

        .topic-item:nth-of-type(4n + 0) {
          margin-right: 0px;
        }
      }

      .img-item {
        width: 110px;
        margin-right: 10px;
        height: 110px;
        opacity: 1;
        border-radius: 10px;
        background: rgba(229, 229, 229, 1);
        margin-top: 18px;
        // margin-left: 10px;
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;

        > img {
          width: 25px;
          height: 62.78px;
          opacity: 1;
        }

        > div {
          position: absolute;
          right: 5px;
          bottom: 5px;
          font-size: 16px;
          font-weight: 500;
          letter-spacing: 0px;
          line-height: 23.17px;
          color: rgba(166, 166, 166, 1);
        }
      }

      .img-list {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex-wrap: wrap;

        .img-item-detail {
          width: calc((100%) / 3);
          //width: 110px;
          //margin-right: 10px;
          height: 110px;
          opacity: 1;
          border-radius: 10px;
          margin-top: 18px;

          > img {
            width: 100%;
            height: 122px;
            background-size: 100%;
            background-repeat: no-repeat;
          }

          .delIcon {
            position: absolute;
            top: 20px;
            right: 5px;
          }
        }

        .img-item-detail:nth-of-type(3n + 0) {
          margin-right: 0px;
        }
      }
    }

    .is_lock {
      padding: 10px 10px;
      font-size: 12px;
      font-weight: 500;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      color: #a6a6a6;


      /deep/ .van-cell {
        font-size: 17px;
        padding: 0;
      }

      > span {
        margin-right: 15px;
      }

      > div {
        display: flex;
        justify-content: center;
        align-items: center;

        img {
          width: 12px;
          height: 12px;
        }
      }
    }
  }

  .footer {
    display: flex;
    justify-content: center;
    padding-top: 43px;

    .btn {
      width: 141px;
      height: 38px;
      line-height: 38px;
      opacity: 1;
      border-radius: 19px;
      background: rgba(242, 150, 0, 1);
      font-size: 23px;
      font-weight: 500;
      color: rgba(255, 255, 255, 1);
      text-align: center;
    }
  }

  .hide_file {
    display: none;
  }
}
</style>
